package com.example.pungolo.journal;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.example.pungolo.journal.model.DateUtils;
import com.example.pungolo.journal.model.DiaryEntry;
import com.example.pungolo.journal.model.DiaryIO;
import com.example.pungolo.journal.model.DiaryPage;
import com.example.pungolo.journal.model.Mood;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.ViewSwitcher;

public class EntryActivity extends Activity {

  private final static DateFormat dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG);
  private final static DateFormat timeFormat = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT);

  SharedPreferences settings;

  final static int MOOD_UI_REQUEST = 1;
  final static int SHARE_REQUEST = 2;
  final static int CAMERA_UI_REQUEST = 4;

  private int moodResourceId;
  private String textOfTheNote;
  private String dailyImagePath = null;
  private Uri newPhotoPath = null;
  private DiaryPage page;
  private DiaryEntry entry;
  private boolean edited = false;
  AlertDialog.Builder cancelAlertBuilder;
  private Button saveButton;
  private Button cancelButton;
  private TextView dateView;
  private TextView timeView;
  private ImageView moodView;
  private TextView noteView;
  private ImageView shareButton;
  private ImageView dailyImage;
  private EditText noteEditor;
  private ViewSwitcher noteEditSwitch;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    settings = getSharedPreferences("settings", 0);

    Intent caller = getIntent();
    if (caller.hasExtra("entryDate")) {
      long longDate = caller.getLongExtra("entryDate", -1);
      Date entryDate = new Date(longDate);
      this.page = DiaryIO.getDatabase().getDiaryPageFromDate(entryDate);
      this.entry = page.getDiaryEntryByDate(entryDate);
    } else {
      Date entryDate = new Date();
      this.page = DiaryIO.getDatabase().getDiaryPageFromDate(entryDate);
      this.entry = new DiaryEntry();
      this.entry.setDate(entryDate);
      this.entry.setMood(Mood.uncertain);
      this.entry.setText("");
    }

    setContentView(R.layout.activity_entry);

    cancelAlertBuilder = new AlertDialog.Builder(this);
    cancelAlertBuilder.setMessage("Are you sure you want to lose all the changes you made?");
    cancelAlertBuilder.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
        onCancelClicked();
      }
    });
    cancelAlertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
      }
    });

    this.saveButton = (Button) findViewById(R.id.entryUI_save_button);
    this.cancelButton = (Button) findViewById(R.id.entryUI_cancel_button);
    this.dateView = (TextView) findViewById(R.id.entryUI_dateTextView);
    this.timeView = (TextView) findViewById(R.id.entryUI_timeTextView);
    this.moodView = (ImageView) findViewById(R.id.entryUI_moodImage);
    this.noteView = (TextView) findViewById(R.id.entryUI_note_text_view);
    this.shareButton = (ImageView) findViewById(R.id.entryUI_share);
    this.dailyImage = (ImageView) findViewById(R.id.entryUI_dayPicture);
    this.noteEditor = (EditText) findViewById(R.id.entryUI_note_edit_view);
    this.noteEditSwitch = (ViewSwitcher) findViewById(R.id.entryUI_textSwitcher);

    // date

    dateView.setText(dateFormat.format(page.getDate()));
    timeView.setText(timeFormat.format(page.getDate()));

    if (savedInstanceState != null && savedInstanceState.containsKey("newImagePath"))
      newPhotoPath = Uri.parse(savedInstanceState.getString("newImagePath"));
    // picture of the day

    File imgFile;
    if (savedInstanceState != null && savedInstanceState.containsKey("imagePath"))
      dailyImagePath = savedInstanceState.getString("imagePath");
    else
      dailyImagePath = page.getImagePath();

    if (dailyImagePath != null) {

      imgFile = new File(dailyImagePath);
      if (imgFile.exists()) {
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        dailyImage.setImageBitmap(myBitmap);
      }
    }

    // mood
    if (savedInstanceState != null && savedInstanceState.containsKey("mood"))
      moodResourceId = savedInstanceState.getInt("mood");
    else
      moodResourceId = entry.getMood().res;
    moodView.setImageResource(moodResourceId);

    // note
    if (savedInstanceState != null && savedInstanceState.containsKey("textNote"))
      textOfTheNote = savedInstanceState.getString("textNote");
    else
      textOfTheNote = entry.getText();
    noteView.setText(textOfTheNote);
    if (userCanEditEntry())
      showNoteEditor();

    moodView.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        if (userCanEditEntry())
          onMoodClicked();
      }
    });
    dailyImage.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        onDailyImageClick();
      }
    });
    noteView.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        if (userCanEditEntry())
          onTextViewClicked(v);
      }
    });
    shareButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        onShareClicked();
      }
    });
    cancelButton.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        onBackPressed();
      }
    });
    saveButton.setOnClickListener(new OnClickListener() {
      public void onClick(View arg0) {
        onSaveClicked();
      }
    });
    noteEditor.setOnFocusChangeListener(new OnFocusChangeListener() {
      public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
          onExitedEditor();
        }
      }
    });
    noteEditor.setOnEditorActionListener(new OnEditorActionListener() {
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
          onExitedEditor();
          return true;
        }
        return false;
      }
    });
    if (itsNotToday())
      saveButton.setEnabled(false);

  }

  protected void onSaveInstanceState(Bundle icicle) {
    super.onSaveInstanceState(icicle);
    if (dailyImagePath != null)
      icicle.putString("imagePath", dailyImagePath);
    if (newPhotoPath != null)
      icicle.putString("newImagePath", dailyImagePath);
    icicle.putInt("mood", moodResourceId);
    icicle.putString("textNote", textOfTheNote);
  }

  private void clearEditViewFocus() {
    EditText t = (EditText) findViewById(R.id.entryUI_note_edit_view);
    if (t.hasFocus())
      t.clearFocus();
  }

  protected boolean userCanEditEntry() {
    int graceTime = settings.getInt(SettingsActivity.GRACE_TIME, 5);
    Calendar c = Calendar.getInstance();
    c.setTime(this.entry.getDate());
    c.add(Calendar.MINUTE, graceTime);
    boolean result = c.getTime().compareTo(new Date()) > 0;
    return result;
  }

  protected boolean itsNotToday() {
    int entryday = DateUtils.dayFromDate(page.getDate());
    return (entryday != DateUtils.today());
  }

  protected void onExitedEditor() {
    this.noteEditSwitch.showPrevious();
    String newText = this.noteEditor.getText().toString();
    this.noteView.setText(newText);
    if (!this.entry.getText().equals(newText)) {
      this.edited = true;
      this.entry.setText(newText);
    }
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(this.noteEditor.getWindowToken(), 0);

  }

  protected void onDailyImageClick() {

    if (itsNotToday())
      return;

    // clear focus of editView if it has focus
    clearEditViewFocus();

    // open camera activity
    Intent openUI4 = new Intent(getApplicationContext(), CameraActivity.class);
    openUI4.putExtra("imagePath", page.getImagePath());
    startActivityForResult(openUI4, 4);

  }

  protected void onMoodClicked() {
    if (!userCanEditEntry())
      return;

    clearEditViewFocus();

    Intent openUI3 = new Intent(getApplicationContext(), MoodSelectionActivity.class);
    startActivityForResult(openUI3, 1);
  }

  protected void onCancelClicked() {
    super.onBackPressed();
  }

  protected void onSaveClicked() {

    Intent back = new Intent();
    if (newPhotoPath != null) {
      back.putExtra(android.content.Intent.EXTRA_TEXT, newPhotoPath.getPath());
    }
    clearEditViewFocus();
    this.entry.save();
    this.setResult(RESULT_OK, back);
    finish();
  }

  protected void onShareClicked() {
    // clear focus of editView if it has focus
    clearEditViewFocus();

    // share activity
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("text/plain");
    View v = findViewById(R.id.entryUI_note_text_view);
    TextView noteText = (TextView) v;
    String s = noteText.getText().toString();

    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, s);

    Log.i("pungolo-journal", "Calling intent for sharing \"" + s + "\"");
    startActivityForResult(Intent.createChooser(sharingIntent, "Share via"), SHARE_REQUEST);
  }

  private void showNoteEditor() {
    this.noteEditSwitch.showNext();
    this.noteEditor.setText(this.noteView.getText());
    this.noteEditor.requestFocus();
  }

  private void onTextViewClicked(View v) {
    if (!userCanEditEntry())
      return;

    // edit note
    showNoteEditor();
  }

  public void onBackPressed() {
    if (edited)
      cancelAlertBuilder.show();
    else {
      super.onBackPressed();
      if (newPhotoPath != null)
        deleteOldPicture(newPhotoPath.getPath());
    }
  }

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i("pungolo-journal", "rc=" + requestCode);
    // result of moodUISelection
    if (requestCode == MOOD_UI_REQUEST) {
      if (resultCode == RESULT_OK) {
        int moodId = data.getIntExtra("mood_id", -1);
        ImageView mood = (ImageView) findViewById(R.id.entryUI_moodImage);
        mood.setImageResource(moodId);
        Mood m = Mood.getMoodFromRes(moodId);
        if (this.entry.getMood().id != m.id) {
          edited = true;
          this.entry.setMood(m);
        }
      }
    }
    if (requestCode == SHARE_REQUEST) {
    }
    if (requestCode == CAMERA_UI_REQUEST) {
      if (resultCode == RESULT_OK) {

        if (data != null && data.hasExtra(android.content.Intent.EXTRA_TEXT)) {
          dailyImagePath = data.getStringExtra(android.content.Intent.EXTRA_TEXT);
          newPhotoPath = Uri.parse(dailyImagePath);
        }

        if (dailyImagePath != null) {
          dailyImage.setImageURI(Uri.parse(dailyImagePath));

        }

      }
    }

  }// onActivityResult

  private void deleteOldPicture(String picturePath) {
    if (picturePath == null)
      return;
    File f = new File(picturePath);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
      return;

    // Attempt to delete it
    f.delete();

  }
}
